import {
  PlusOutlined,
  TagsOutlined,
  QuestionCircleOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Avatar, Modal, Tag, Tooltip} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import debounce  from 'lodash.debounce';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import UploadModel from './components/UploadModel';
import RenameForm from './components/RenameForm';
import TagCommonComponent from '../System/components/TagCommonComponent';
import AssignTagsModel from '../System/components/AssignTagsModel';
import ProgramModel from './components/ProgramModel';
import { TableListItem } from './data.d';
import { materialList, materialRemove, batchDelete, rename, setTag} from './service';
import styles from './index.less';

const { Search } = Input;
const { Option } = Select;

const MaterialList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<TableListItem>();
  const [renameModalVisible, handleRenameModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [tagEnabled, handleTagEnabled] = useState<boolean>(true);
  const [topOrgId, setTopOrgId] = useState<number>(0);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [assignTagModalVisible, handleAssignTagModalVisible] = useState<boolean>(false);
  const [programModalVisible, handleProgramModalVisible] = useState<boolean>(false);

  const tagControl = () =>{
    if(selectedRowKeys.length>0){
      for(let i in selectedRows){
        if(parseInt(i)>0){
          const row1 = selectedRows[parseInt(i)-1];
          const row = selectedRows[i];
          if(row1.topOrgId != row.topOrgId){
            handleTagEnabled(true);
            return;
          }
        }
      }
      setTopOrgId(selectedRows[0].topOrgId);
      handleTagEnabled(false);
    }else{
      handleTagEnabled(true);
    }
  }

  useEffect(() => {
    tagControl();
  },[selectedRowKeys,selectedRows]);

 //标签选中监听
  const selectChange = (values:any,form:any) => {
    form.setFieldsValue({"tagIds": values.toString()});
    form.submit();
  }

  //删除
  const delConfirm = (id: number) => {
    console.log(selectedRowKeys);
    console.log(selectedRows)
    const param = new Object();
    param["id"] = id;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此素材将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          materialRemove(param)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowKeys.length > 0) {
                    for (let i in selectedRowKeys) {
                      if (selectedRowKeys[i] == id) {
                        selectedRowKeys.splice(parseInt(i), 1);
                      }
                    }
                  }
                  hide();
                  if (selectedRowKeys.length == 0) {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    const newRows = selectedRows.concat();
                    for(let i=0;i<selectedRows.length;i++){
                      if(selectedRows[i].id == id){
                        newRows.splice(i, 1);
                      }
                    }
                    setSelectedRows(newRows);
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
                } else {
                  message.error('删除失败，'+res.message);
                  resolve(false);
                }
              }
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      },
    });
  };

  //批量删除
  const delConfirmBatch = (ids: string) => {
    const param = new Object();
    param["ids"] = ids;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此素材将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          batchDelete(param)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  const errList = res.data;
                  if(errList.length == 0){
                    message.success("删除成功",1);
                  }else{
                    let mes = "";
                    for(let i in errList){
                      for(let j in selectedRows){
                        if(parseInt(selectedRows[j].id) == errList[i]){
                          mes += selectedRows[j].filename + '，';
                        }
                      }
                    }
                    mes = mes + "删除失败";
                    message.error(mes,2);
                  }
                  handleDeleteModalVisible(false);
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                  resolve(true);
                } else {
                  message.error('删除失败，'+res.message);
                  resolve(false);
                }
              }else{
                message.error('删除失败');
                  resolve(false);
              }
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      },
    });
  };
  //上传成功
  const uploadFinish = async (callback: string) => {
    if (callback == 'success') {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  //重命名，确定按钮点击
  const handleUpdate = async (values: TableListItem) => {
    if (values != null && values != undefined) {
      let params = new Object();
      params['name'] = values.name;
      params['id'] = values.id;
      params['code'] = values.code;
      new Promise((resolve, reject) => {
        rename(params)
          .then((res) => {
            if (res.code === 200) {
              message.success('修改成功');
              handleRenameModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
              resolve(true);
            } else if (res.code == 4501) {
              message.error('素材使用中，不能修改');
              resolve(false);
            } else {
              message.error('修改失败，'+res.message);
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  };

  const handleCancel = () => {
    handleRenameModalVisible(false);
  };

  //分配标签
  const assignTagCommand = (values:any) => {
    const tagsParam = new Object;
    tagsParam["materialIds"] = selectedRowKeys.toString();
    tagsParam["tagIds"] = values.toString();
    new Promise((resolve, reject) => {
      setTag(tagsParam)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('分配成功');
              handleAssignTagModalVisible(false);
              setSelectedRowKeys([]);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
              hide();
              resolve(true);
            } else {
              message.error('分配失败，' + res.message);
              resolve(false);
            }
          } 
        })
        .catch((error) => {
          message.error('删除失败');
          reject(error);
        });
    });
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '缩略图',
      dataIndex: 'thumbStoreId',
      valueType: 'avatar',
      hideInSearch: true,
      className: styles.thumb,
      render: (_, record) => <Avatar src={record.urlPrefix + record.thumbStoreId} shape="square" size="large" />,
    },
    {
      title: '素材名称',
      dataIndex: 'filename',
      // ellipsis: {
      //   showTitle: false,
      // },
      ellipsis:true,
      width:150,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入素材名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      // render: filename => (
      //   <Tooltip placement="topLeft" title={filename}>
      //     {filename}
      //   </Tooltip>
      // ),
      valueType: 'text',
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '大小',
      dataIndex: 'size',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '时长',
      dataIndex: 'duration',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'text',
      hideInSearch: true, 
      valueEnum: {
        USING: { text: '使用中', status: 'Success' }, //status显示状态
        UNUSED: { text: '未使用', status: 'Default' },
      },
    },
    {
      title: '引用节目',
      dataIndex: 'template',
      valueType: 'text',
      hideInSearch: true,
      render: (_, record) => 
      <>
        <a
          type="primary"
          onClick={()=>{
            setFormValues(record);
            handleProgramModalVisible(true);
          }}>查看
        </a>
      </>,
    },
    {
      title: '素材类型',
      dataIndex: 'type',
      hideInTable: true, 
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              style={{ width: 200 }}
              placeholder="请选择"
              optionFilterProp="children"
              onChange={(value) => form.submit()}
              // onSearch={(value) => form.submit()}
            >
              <Option value="">全部</Option>
              <Option value="IMAGE">图片</Option>
              <Option value="VIDEO">视频</Option>
              {/* <Option value="AUDIO">音频</Option> */}
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
              <TagCommonComponent
                topOrgId = {JSON.parse(localStorage.getItem("user")).topOrgId}
                selectChange={(values) => selectChange(values,form)}
              >
              </TagCommonComponent>
          );

        }
        return defaultRender(_);
      },
      hideInTable:true,
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width:150,
      hideInSearch: true, 
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={tag.name} style={{marginBottom:5,display:'inline-block',overflow:'hidden',whiteSpace:'pre',textOverflow:'ellipsis',maxWidth:130}}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a href={record.urlPrefix + record.storeId} target="_blank">
            预览
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleRenameModalVisible(true);
              setFormValues(record);
            }}
          >
            重命名
          </a>
          <Divider type="vertical" />
            <a href={"/material/download/" + record.storeId} download={record.originalFilename} target="_blank">
              下载
            </a>
          <Divider type="vertical" />
          <a
            disabled={record.status == 'UNUSED' ? false : true}
            onClick={() => {
              delConfirm(record.id);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{ 
          showQuickJumper: true, 
          defaultPageSize: 10,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 上传素材
          </Button>,
          <Button
            type="primary"
            disabled={tagEnabled}
            onClick={()=> handleAssignTagModalVisible(true)}
            >
            <TagsOutlined /> 分配标签
          </Button>,
          <Button
            type="primary"
            disabled={selectedRowKeys.length > 0 ? false : true}
            onClick={() => delConfirmBatch(selectedRows.map((row) => row.id).toString())}
          >
            <DeleteOutlined /> 批量删除
          </Button>,
        ]}
        request={(params, sorter, filter) => materialList(params, sorter, filter)}
        onLoad={()=>{
          setSelectedRowKeys(selectedRowKeys);
          setSelectedRows(selectedRows);
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys:selectedRowKeys,
          onSelect:(record, selected)=>{
            if(selected){//选中
              setSelectedRowKeys([...selectedRowKeys,record.key]);
              setSelectedRows([...selectedRows,record]);
            }else{//取消选中
              const newKeys = selectedRowKeys.concat();
              const index = newKeys.indexOf(record.key);
              newKeys.splice(index, 1);
              setSelectedRowKeys(newKeys);
              
              const newRows = selectedRows.concat();
              for(let i=0;i<selectedRows.length;i++){
                if(i == index){
                  newRows.splice(index, 1);
                }
              }
              setSelectedRows(newRows);
            }
          },
          onSelectAll:(selected, selectedRows1, changeRows)=>{
            if(selected){//全选
              const keys = [];
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                keys.push(record.key);
              }
              setSelectedRowKeys([...selectedRowKeys,...keys]);
              setSelectedRows([...selectedRows,...changeRows]);
            }else{//取消全选
              const newSelectedRowKeys = selectedRowKeys.concat();
              const newSelectedRows = selectedRows.concat();
              for(let i=0;i<changeRows.length;i++){
                const record = changeRows[i];
                for(let j=0;j<newSelectedRowKeys.length;j++){
                  if(record.key == newSelectedRowKeys[j]){
                    newSelectedRowKeys.splice(j, 1);
                    newSelectedRows.splice(j, 1);
                  }
                }
              }
              setSelectedRowKeys(newSelectedRowKeys);
              setSelectedRows(newSelectedRows);
            }
          }
        }}
        tableAlertOptionRender={() => {
          return (<a onClick={() => {
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.clearSelected?.();
          }}>清空</a>)
        }}
      />
      <UploadModel
        onSubmit={uploadFinish}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      ></UploadModel>
      <RenameForm
        modalVisible={renameModalVisible}
        values={formValues}
        onSubmit={handleUpdate}
        onCancel={handleCancel}
      >
        <ProTable<TableListItem, TableListItem> />
      </RenameForm>
      <AssignTagsModel
        modalVisible={assignTagModalVisible}
        topOrgId={topOrgId}
        onSubmit={assignTagCommand}
        onCancel={()=>handleAssignTagModalVisible(false)}
      >
        <ProTable<TableListItem, TableListItem> />
      </AssignTagsModel>
      <ProgramModel
        modalVisible={programModalVisible}
        id={formValues?.id}
        onCancel={()=>handleProgramModalVisible(false)}
      >
        <ProTable<TableListItem, TableListItem> />
      </ProgramModel>
    </PageContainer>
  );
};

export default MaterialList;
